<template>
  <div class="w_flags" v-transfer-dom>
    <popup v-model="showValue" position="bottom">                
        <divider>常用标签</divider>
        <div class='hScroll'>
            <checker class='hScrollCon' v-model="flagUse" default-item-class="demo1-item" type="checkbox" :max="8" selected-item-class="demo1-item-selected">
                <checker-item :value="it" v-for="(it, index) in flagUseArr" :key="index">{{it.name}}</checker-item>
            </checker>
        </div>
        <divider>项目标签</divider>
        <div class='hScroll'>
            <checker class='hScrollCon' v-model="projectUse" default-item-class="demo1-item" type="checkbox" :max="1" selected-item-class="demo1-item-selected">
                <checker-item v-for="(it, index) in projects" :key="index" :value="it">{{it.title.substr(0,4)}}</checker-item>
            </checker>
        </div>
        <divider>{{ this.task && this.task.parid==null?"重复任务":"不能设置重复"}}</divider>
        <div class='hScroll'>
          <checker class="hScrollCon" style="width:430px;" v-show="this.task && this.task.parid==null" v-model="flagRepeat" default-item-class="demo1-item" type="checkbox" :max="1" selected-item-class="demo1-item-selected">
                <checker-item v-for="(it, index) in tagsRepeat" :key="index" :value="it">{{it.name}}</checker-item>
          </checker>
        </div>
        <divider>所有标签</divider>
          <checker class="checkScroll" v-model="flagUse" default-item-class="demo1-item" type="checkbox" :max="8" selected-item-class="demo1-item-selected">
            <checker-item v-for="(it, index) in tagsAll" :key="index" :value="it">{{it.name}}</checker-item>
        </checker>
        <Group v-if="task">
            <x-input v-model="newTag" placeholder="新建标签">
                <span slot="label" style="padding-right: 6px;font-size: 24px;" class="iconfont icon-add"></span>
                <x-button slot="right" v-show="newTag.trim().length>0" type="primary" @click.native="doAddTag" mini>添加</x-button>
            </x-input>
        </Group>  
        <box v-if="!task" gap="10px 10px">
            <flexbox>
                <flexbox-item>
                  <x-button type="primary" @click.native="doAdd">添加</x-button>
                </flexbox-item>
                <flexbox-item>
                  <x-button type="warn" @click.native="doBack">返回</x-button>
                </flexbox-item>
            </flexbox>
        </box>
        <div class="spacer_v"></div>
    </popup>
  </div>
</template>
<script>
import moment from "moment";

import Vue from 'vue';
import api from '../../api';
import { taskAndTag  } from "../mixin";

import { mapState, mapActions} from 'vuex'


import {
    TransferDomDirective as TransferDom,    
    Box,Popup,XButton, Checker,CheckerItem,Divider,Group,XInput,Flexbox, FlexboxItem
} from 'vux'

export default {
    directives: {
        TransferDom
    },
    components: {    
        Popup,XButton, Checker,CheckerItem,Divider,Group,XInput
        ,Box,Flexbox, FlexboxItem
    },
    props:{        
        task: [Object], 
        show: Boolean,
        ext:Object,
    },
    mixins: [taskAndTag],    
    computed: {       
        "tagsAll":function(){
            var temp=[] ;
            // var filtersFlag = ['created','cancelled','need','done','toggle','due','started','to','by','repeat','used','usedCalc','timeDiff',"wakeup","getup","wash1 ","bath","wc","breakfast","tape","study","gowork","workStart","workReady","health","lunch","cartoon","dinner","workEnd","gohome","wash2","sleep","monday","tuesday","wednesday","thursday","friday","saturday","sunday"] ;
            var len = this.tagitems.length ;
            for(var i=0;i<= len-1 ;i++){
                var item = this.tagitems[i] ;
                if( this.filtersFlag.indexOf(item.key) != -1 ) continue ;
                temp.push({key:item.key,name:item.name}) ;
            }
            return temp ;
        }, 
        ...mapState({
            uid: state => state.vux.uid,
            tagDic: state => state.z39.tagDic,
            
            tagitems: state => state.z39.tagitems,
            tagitemDic: state => state.z39.tagitemDic,
            filtersFlag: state => state.z39.filtersFlag,
            projects:state => state.z39.projects
        })
    },
    watch: {        
        show(val){            
            this.showValue = val ;
            if(val){
              let _this = this;
              this.getTagsrec().then(data => {
                if(data.errno) return ; //this.$vux.toast.show({text: data.errmsg ,type: 'warn'})
                  //data = data.data;
                  this.flagUseArr = data ;
              })
              document.body.append( document.querySelector(`#flags-${this.uuid}`) );
              console.log("show flag:",document.querySelector(`#flags-${this.uuid}`))
            }
        },
        showValue(val){            
            // if( this.showValue == val) return ;
            // return ;
            if(val) this.isCancle = false ;
            // 创建任务中的标签,点击返回按钮
            if(this.isCancle &&!this.showValue) return this.$emit('flaghide',false);
            let temp= [] , tempArr=[] ;
            if( !this.showValue ){  //关闭窗口
                this.$emit('flaghide',false) ; 
                var len = this.flagUse.length ;
                var tags ={};
                for(var i=0;i<= len-1 ;i++){
                    var item = this.flagUse[i] ;
                    temp.push(item.key) ;                    
                    if(!this.task) tags[item.key]="";
                }
                var pid = this.projectUse.length>0?this.projectUse[0].gid:"" ;
                // '正在创建的任务标签'派发事件和数据后跳出逻辑.
                if(!this.task) return this.$emit('ext',{pid,tags}) ;

                let news = _.difference( temp , this.tagsOld ) ;
                let dels = _.difference( this.tagsOld , temp  ) ;
                this.$store.commit(Object.assign({ type: "z39/addTagsres" }, { keys: news }));
                this.tagsAdd(news,false,this.task) ;
                this.tagsDel(dels,false,this.task) ;

                let key = "repeat",value="",day ;
                if( this.flagRepeat.length >0 ){
                    let sdata = this.flagRepeat[0] ;   //选中标签数据对象
                    let rdata = sdata.key ;    //选中标签数据
                    
                    value = rdata.replace("repeat=","");
                    day = moment().format('YYYY-MM-DD');
                    console.log(rdata) ;   //{"repeat":"D"}
                }                
                if(this.task.tags.repeat !=undefined && this.flagRepeat.length ==0){ //删除-原来有现在没有 重复标签
                    this.tagsDel(["repeat"],false,this.task) ;
                    this.repeatDel( {taskid: this.task.id } );
                }else if(this.task.tags.repeat !=undefined && this.flagRepeat.length >0 && this.task.tags.repeat !=value){   // 修改-重复标签.
                    this.doTagSet(this.task,key,value) ;
                    this.repeatSet( {taskid:  this.task.id , rule:value, time_rule: day } );
                }else if(this.task.tags.repeat ==undefined && this.flagRepeat.length >0){  //增加
                    this.tagAdd({key,value},true,this.task);
                     this.repeatAdd( {taskid:  this.task.id , rule:value, time_rule: day } );
                }
                if( this.task.pid != pid){
                    if( !this.task.pid && !pid) return; // 跳出pid=null pid=""进入逻辑.
                    api.taskSet({id:this.task.id,pid:pid}).then(data=>{
                        if (data == undefined || data.errno != 0) return ;
                        // this.$store.commit(Object.assign({ type: "z39/taskSet" }, {pid:pid}, { task: this.task }));
                        Vue.set(this.task, "pid", pid);
                        if( news.length== 0&& dels.length== 0) this.$vux.toast.show({ text: "设置成功", type: "success" })
                    })
                }
                console.log("showValue",news ,dels , temp ,this.tagsOld);
                // this.show= false ;
                // this.$emit('update:show', false) ;
            }else{  //打开窗口,保存临时值,做后期比对.
                // if(!this.task)// return ; //正在创建任务的标签
                var target = !this.task?this.ext:this.task;
                var tags = target.tags || {} ;
                for( var key in tags){
                    temp.push({key:key,name: this.tagitemDic[key] });
                    tempArr.push(key) ;
                    if(key=="repeat"){
                        let tempKey = key+"="+tags[key]; 
                        let select = this.tagsRepeat.filter( item=>{ return item.key == tempKey});
                        this.flagRepeat = select; // [{key:,name: this.tagitemDic[key]}];
                        console.log( key+tags[key],select) ;  
                    }
                }
                if(target.pid){
                    var itemp ;
                    for (var i = this.projects.length - 1; i >= 0; i--) {
                        if(this.projects[i].gid == target.pid) {
                            itemp = this.projects[i] ;
                            break ;
                        } 
                    };
                    if(itemp!=null) this.projectUse = [itemp] ;
                }
                this.flagUse = temp ;
                this.tagsOld = tempArr ;
                // this.$emit('flaghide',true) ; 
            }
        }
    },
    created() {
      
    },
    activated(){
        
    },
    mounted: function() {
        this.uuid = Math.random().toString(36).substring(3, 8);
        this.$el.setAttribute('id', `flags-${this.uuid}`);
    },
    methods: {
        doAddTag(){
            if( this.newTag.trim().length == 0 ){
                return this.$vux.toast.show({text:"不能为空",type: 'warn'})
            }
            this.newTag = this.newTag.trim() ;
            let tkey = pinyin.getFullChars(this.newTag) ; //index.html中引入的pinyin.js
            if( this.tagDic[tkey] != undefined ){
                return this.$vux.toast.show({text:"请重新取名",type: 'warn'})
            }
            let tagdata = {key:tkey,name:this.newTag} ;
            api.tagitemAdd(tagdata).then(data=>{
                if (data == undefined || data.errno != 0) {
                  if (data == undefined) data = { errmsg: "网络错误" };
                  return this.$vux.toast.show({text:data.errmsg,type: 'warn'})
                }
                tagdata.id = data.data ;                
                var mitem = {key:tagdata.key, name:tagdata.name};
                this.flagUseArr.unshift(mitem);
                this.flagUse.push(mitem);
                this.$store.commit({
                  type: "z39/tagitemsAdd",
                  tagitems: [tagdata]
                });
                this.newTag = "" ;
                // console.log(data);
            }) ;
            // console.log(this.newTag);
        },
        doAdd(){
            this.showValue = false ;
        },
        doBack(){
            this.isCancle = true ;
            this.showValue = false ;
        },
        doClear(){
            this.flagUse = [] ;
        },
        ...mapActions([
            
        ])
    },
    data() {
        return {
            uuid:"",
            taskitem:{},
            flagUse:[],
            flagUseArr:[], //[{name: "评估",key:"need"},{name: "分解"},{name: "合并"}],
            flagProArr:[], //[{name: "学习"},{name: "测试"},{name: "开发"},{name: "美术"},{name: "产品"},{name: "运营"}],
            flagAllArr:[], //[{name: "评估"},{name: "分解"},{name: "合并"},{name: "学习"},{name: "测试"},{name: "开发"},{name: "美术"},{name: "产品"},{name: "运营"},{name: "学习"},{name: "测试"},{name: "开发"},{name: "美术"},{name: "产品"},{name: "运营"},{name: "学习"},{name: "测试"},{name: "开发"},{name: "美术"},{name: "产品"},{name: "运营"}],
            tagsOld:[],
            flagRepeat:[],
            tagsRepeat:[{name:"每天",key:"repeat=D"},{name:"每周1",key:"repeat=W1"},{name:"每周2",key:"repeat=W2"},{name:"每周3",key:"repeat=W3"},{name:"每周4",key:"repeat=W4"},{name:"每周5",key:"repeat=W5"},{name:"每周6",key:"repeat=W6"},{name:"每周日",key:"repeat=W7"},{name:"每月",key:"repeat=M"},{name:"每年",key:"repeat=Y"},],
            showValue:false,
            newTag:"",
            projectUse:[],
            isCancle:false,
        }
    }
}

</script>
<style scoped>

.checkScroll{max-height: 200px;    overflow: scroll;}
.demo1-item {
        border: 1px solid #027ab7;
    border-radius: 4px;
    padding: 0 6px 4px 4px;
    margin: 1px 2px;
    padding: 0 4px;
    line-height: 31px;
    height: 31px;
    width: auto;
    text-align: center;
    font-size: 12px;
}

.demo1-item-selected {
    border: 1px solid #8e8e8e;
    background-color: #10aeff;
}

.customChe {
    border: 1px solid #b2b2b2;
    background-color: #ffffff;
    width: 40px;
    text-align: center;
}
.hScroll{
    overflow: scroll;   
	white-space: nowrap;
}
.hScrollCon{
    display: flex;
}


</style>
<style>
    .w_flags .weui-cells{margin-top: 1px;}
    .w_flags .vux-x-input{height:49px;}
</style>